package com.xyxy.platform.website.member.web.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.xyxy.platform.modules.core.beanvalidator.BeanValidators;
import com.xyxy.platform.modules.core.beanvalidator.group.A;
import com.xyxy.platform.modules.core.beanvalidator.group.B;
import com.xyxy.platform.modules.core.file.SystemFileService;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.bind.annotation.CurrentUser;
import com.xyxy.platform.modules.core.web.controller.BaseController;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.entity.IsDelete;
import com.xyxy.platform.modules.entity.content.Article;
import com.xyxy.platform.modules.entity.image.ImageItem;
import com.xyxy.platform.modules.entity.image.ImageTypes;
import com.xyxy.platform.modules.entity.trade.*;
import com.xyxy.platform.modules.service.content.ArticleService;
import com.xyxy.platform.modules.service.image.ImageItemService;
import com.xyxy.platform.modules.service.trade.CategoryService;
import com.xyxy.platform.modules.service.trade.GoodsServerTimeService;
import com.xyxy.platform.modules.service.trade.GoodsService;
import com.xyxy.platform.modules.service.trade.ServerTagService;
import com.xyxy.platform.modules.service.trade.vo.GoodsDto;
import com.xyxy.platform.website.common.vo.CurrentLoginUser;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 简介: 会员服务管理
 *
 * @author Caizhenegda
 * @version 1.0
 * @Date 2016-01-06 20:16
 */
@Controller
@RequestMapping("/member")
public class ServiceManagerController extends BaseController {

    @Autowired
    private Validator validator;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ImageItemService imageItemService;

    @Autowired
    private SystemFileService systemFileService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private GoodsServerTimeService goodsServerTimeService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ServerTagService serverTagService;

    /**
     * 跳转至 服务管理页面
     *
     * @return
     */
    @RequestMapping(value = "service/manage", method = RequestMethod.GET)
    public String serviceManagerView() {
        return "member/service_manage";
    }

    /**
     * 跳转至 服务发布页面
     *
     * @return
     */
    @RequestMapping(value = "service/publish", method = RequestMethod.GET)
    public String servicePublishView() {
        return "member/service_publish";
    }

    /**
     * 跳转至 服务编辑页面
     *
     * @return
     */
    @RequestMapping(value = "service/edit/{goodsId}", method = RequestMethod.GET)
    public String serviceEditView(@CurrentUser CurrentLoginUser user, @PathVariable Long goodsId, Model model) {
        boolean isExist = goodsService.isExist(goodsId, user.getId());
        if (!isExist) return this.page404;

        model.addAttribute("goodsId", goodsId);
        return "member/service_edit";
    }

    /**
     * 服务查询
     *
     * @param user   当前登录用户
     * @param isSale 上架状态, 关闭, 开启:对应 0:下架, 上:下架.
     * @return
     */
    @ResponseBody
    @RequestMapping("goods/query")
    public ResponseMessage<?> goodsSearch(
            @CurrentUser CurrentLoginUser user,
            @RequestParam(defaultValue = "0") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Integer isSale) {

        Goods params = new Goods();
        params.setMemberId(user.getId());
        params.setIsDel(IsDelete.NO.ordinal());
        if (null != isSale) params.setIsSale(isSale);
        List<Goods> list = goodsService.selectByGoods(pageNum + 1, pageSize, params);

        PageInfo pageInfo = new PageInfo(list);

        List<Map<String, Object>> dataList = Lists.newArrayList();
        for (Goods goods : list) {
            Map<String, Object> map = Collections3.transBean2Map(goods);
            //封面图片最多五张取第一张
            List<ImageItem> imageItemList = imageItemService.findImageItemList(goods.getGoodsImgPkgid(), ImageTypes.GOODS_COVERS_IMAGES);
            String imageUrl = null;
            if (Collections3.isNotEmpty(imageItemList)) {
                imageUrl = systemFileService.getFileUrlByUri(imageItemList.get(0).getUri());
            }
            map.put("imageUrl", imageUrl);
            dataList.add(map);
        }
        pageInfo.setList(dataList);
        return ResponseUtils.jsonSuccess(pageInfo, "服务查询成功!");
    }

    /**
     * 加载服务时间段定义
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "service/load/server_time_define", method = RequestMethod.GET)
    public ResponseMessage<?> loadGoodsServerTimeDefine() {
        List<Map<String, Object>> values = Lists.newArrayList();
        for (GoodsServerTimeDefine define : GoodsServerTimeDefine.values()) {
            values.add(ImmutableMap.<String, Object>of("idx", define.getIdx(), "rangeDesc", define.getRangeDesc()));
        }
        return ResponseUtils.jsonSuccess(values, "加载时间段定义成功!");
    }

    /**
     * 服务保存, 提交至至审核
     *
     * @param user
     * @param json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "service/save", method = RequestMethod.POST)
    public ResponseMessage<?> save(@CurrentUser CurrentLoginUser user, String json) {
        SaveGoodsForm form = JSON.parseObject(json, SaveGoodsForm.class);
        BeanValidators.validateWithException(validator, form, A.class);
        GoodsDto goodsDto = new GoodsDto();
        goodsDto.setGoodsName(form.getTitle());
        goodsDto.setContent(form.getContent());
        goodsDto.setGoodPrice(form.getPrice());
        goodsDto.setGoodUnit(form.getPriceUnit());
        goodsDto.setTime(form.getDate1());
        goodsDto.setTimeNote(form.getDate2());
        goodsDto.setType(form.getServerType());
        goodsDto.setCateId(form.getCategoryId());
        goodsDto.setGoodPics(form.getImages().split(","));
        goodsDto.setMemberId(user.getId());
        goodsDto.setMemberName(user.getName());
        goodsDto.setTags(form.getTags());
        boolean result = goodsService.saveGoods(goodsDto);
        if (result) {
            return ResponseUtils.jsonSuccess(null, "保存成功!");
        }
        return ResponseUtils.jsonFail(null, "保存失败!");
    }

    /**
     * 服务更新, 提交至至审核
     *
     * @param user
     * @param json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "service/update", method = RequestMethod.POST)
    public ResponseMessage<?> update(@CurrentUser CurrentLoginUser user, String json) {
        SaveGoodsForm form = JSON.parseObject(json, SaveGoodsForm.class);
        BeanValidators.validateWithException(validator, form, B.class);
        GoodsDto goodsDto = new GoodsDto();
        goodsDto.setGoodId(form.getGoodsId());
        goodsDto.setGoodsName(form.getTitle());
        goodsDto.setContent(form.getContent());
        goodsDto.setGoodPrice(form.getPrice());
        goodsDto.setGoodUnit(form.getPriceUnit());
        goodsDto.setTime(form.getDate1());
        goodsDto.setTimeNote(form.getDate2());
        goodsDto.setType(form.getServerType());
        goodsDto.setCateId(form.getCategoryId());
        goodsDto.setGoodPics(form.getImages().split(","));
        goodsDto.setMemberId(user.getId());
        goodsDto.setMemberName(user.getName());
        goodsDto.setTags(form.getTags());
        boolean result = goodsService.updateGoods(goodsDto);
        if (result) {
            return ResponseUtils.jsonSuccess(null, "更新成功!");
        }
        return ResponseUtils.jsonFail(null, "更新失败!");
    }


    /**
     * 服务删除(逻辑删除)
     *
     * @param user    当前登录用户
     * @param goodsId 服务ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "service/delete", method = RequestMethod.POST)
    public ResponseMessage<?> delete(@CurrentUser CurrentLoginUser user, @RequestParam Long goodsId) {
        Goods goods = goodsService.selectByPrimaryId(goodsId);
        if (null != goods && goods.getMemberId() == user.getId()) {
            Goods setValue = new Goods();
            setValue.setIsDel(IsDelete.YES.ordinal());
            goodsService.update(goodsId, user.getId(), setValue);
        } else {
            return ResponseUtils.jsonFail(null, "没有删除该服务得权限, 或该服务已不存在!");
        }
        return ResponseUtils.jsonSuccess(null, "删除服务成功!");
    }

    /**
     * 开启, 关闭服务
     *
     * @param user    当前登录用户
     * @param goodsId 服务ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "service/is_sale", method = RequestMethod.POST)
    public ResponseMessage<?> updateIsSale(@CurrentUser CurrentLoginUser user, @RequestParam Long goodsId, @RequestParam Integer isSale) {
        Goods goods = goodsService.selectByPrimaryId(goodsId);
        if (null != goods && goods.getMemberId().equals(user.getId())) {
            Goods setValue = new Goods();
            setValue.setIsSale(isSale);
            goodsService.update(goodsId, user.getId(), setValue);
        } else {
            return ResponseUtils.jsonFail(null, "没有关闭|开启该服务得权限, 或该服务已不存在!");
        }
        return ResponseUtils.jsonSuccess(null, (isSale == 1 ? "开启" : "关闭") + "服务!");
    }

    /**
     * 根据服务ID查询
     *
     * @param user    当前登录用户
     * @param goodsId 服务ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "service/goods_by_id", method = RequestMethod.GET)
    public ResponseMessage<?> findGoodsById(@CurrentUser CurrentLoginUser user, @RequestParam Long goodsId) {
        Goods goods = goodsService.findByIdAndMemberId(goodsId, user.getId());
        if (null == goods) ResponseUtils.jsonFail("not found!");

        Map<String, Object> goodsMap = Collections3.transBean2Map(goods);

        //分类, 一二级, 一级根据二级的parent获得
        List<Category> categories = Lists.newArrayList();
        if (null != goods.getCatId()) {
            Category category1 = categoryService.findById(goods.getCatId());
            if(null != category1) {
                categories.add(categoryService.findById(category1.getPid()));
            }
            categories.add(category1);
        }
        goodsMap.put("categories", categories);

        //服务时间
        List<GoodsServerTime> goodsServerTimeList = goodsServerTimeService.findByGoodsId(goodsId);
        goodsMap.put("goodsServerTimeList", goodsServerTimeList);

        //服务标题图
        List<ImageItem> imageItemList = imageItemService.findImageItemList(goods.getGoodsImgPkgid(), ImageTypes.GOODS_COVERS_IMAGES);
        for (ImageItem imageItem : imageItemList) {
            imageItem.setUri(systemFileService.getFileUrlByUri(imageItem.getUri()));
        }
        goodsMap.put("imageItemList", imageItemList);

        //具体内容 服务详情
        Article article = articleService.selectById(goods.getGoodsArticleId());
        goodsMap.put("article", article);

        //标签
        List<ServerTags> tagList = serverTagService.findByGoodsId(goods.getGoodsId());
        goodsMap.put("tagList", tagList);

        return ResponseUtils.jsonSuccess(goodsMap, "根据ID查询服务成功!");
    }


}

/**
 * 服务保存表单
 */
class SaveGoodsForm implements Serializable {

    @NotNull(groups = {B.class})
    private Long goodsId;
    @NotNull(groups = {A.class, B.class})
    @Length(min = 2, max = 20)
    private String title;       // 标题
    @NotNull(groups = {A.class, B.class})
    private Long categoryId;    // 分类
    @NotNull(groups = {A.class, B.class})
    private Float price;        // 价格
    @NotNull(groups = {A.class, B.class})
    private String priceUnit;   // 价格单位
    @NotNull(groups = {A.class, B.class})
    private String date1;         // 服务时间段
    private String date2;         // 或服务时间 一版不做
    @NotNull(groups = {A.class, B.class})
    private Integer serverType;  // 服务方式  1上门, 2预定地点, 3线上服务, 4邮寄
    @NotNull(groups = {A.class, B.class})
    private String images;      // 图片 逗号(',')分隔
    @NotNull(groups = {A.class, B.class})
    private String content;     // 服务内容 HTML
    @NotNull(groups = {A.class, B.class})
    private String tags;        // 服务标签 逗号(',')分隔
    private String cases;       // 具体案例 HTML一版不做
    @NotNull(groups = {A.class, B.class})
    private Integer status;      // 0草稿, 1正常

    public Long getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(Long goodsId) {
        this.goodsId = goodsId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Long getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Long categoryId) {
        this.categoryId = categoryId;
    }

    public String getImages() {
        return images;
    }

    public void setImages(String images) {
        this.images = images;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPriceUnit() {
        return priceUnit;
    }

    public void setPriceUnit(String priceUnit) {
        this.priceUnit = priceUnit;
    }

    public String getDate1() {
        return date1;
    }

    public void setDate1(String date1) {
        this.date1 = date1;
    }

    public String getDate2() {
        return date2;
    }

    public void setDate2(String date2) {
        this.date2 = date2;
    }

    public Integer getServerType() {
        return serverType;
    }

    public void setServerType(Integer serverType) {
        this.serverType = serverType;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getTags() {
        return tags;
    }

    public void setTags(String tags) {
        this.tags = tags;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getCases() {
        return cases;
    }

    public void setCases(String cases) {
        this.cases = cases;
    }

}
